package com.css.zfzx.sjcj.modules.hddcB4_SampleResultTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB4_SampleResultTable.repository.HddcB4SampleresulttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB4_SampleResultTable.repository.HddcB4SampleresulttableRepository;
import com.css.zfzx.sjcj.modules.hddcB4_SampleResultTable.repository.entity.HddcB4SampleresulttableEntity;
import com.css.zfzx.sjcj.modules.hddcB4_SampleResultTable.service.HddcB4SampleresulttableService;
import com.css.zfzx.sjcj.modules.hddcB4_SampleResultTable.viewobjects.HddcB4SampleresulttablePageVO;
import com.css.zfzx.sjcj.modules.hddcB4_SampleResultTable.viewobjects.HddcB4SampleresulttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB4_SampleResultTable.viewobjects.HddcB4SampleresulttableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 野外采样数据-样品测试结果表管理
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcB4SampleresulttableServiceImpl implements HddcB4SampleresulttableService {

    private final HddcB4SampleresulttableRepository hddcB4SampleresulttableRepository;
    private final HddcB4SampleresulttableNativeRepository hddcB4SampleresulttableNativeRepository;
    private final FieldSamplingTestResultExcelVerifyHandler fieldSamplingTestResultExcelVerifyHandler;

    @Autowired
    public HddcB4SampleresulttableServiceImpl(HddcB4SampleresulttableRepository hddcB4SampleresulttableRepository,
                                              HddcB4SampleresulttableNativeRepository hddcB4SampleresulttableNativeRepository,
                                              FieldSamplingTestResultExcelVerifyHandler fieldSamplingTestResultExcelVerifyHandler) {
        this.hddcB4SampleresulttableRepository = hddcB4SampleresulttableRepository;
        this.hddcB4SampleresulttableNativeRepository = hddcB4SampleresulttableNativeRepository;
        this.fieldSamplingTestResultExcelVerifyHandler = fieldSamplingTestResultExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcB4Sampleresulttables(HddcB4SampleresulttableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB4SampleresulttablePageVO> hddcB4SampleresulttablePage = this.hddcB4SampleresulttableNativeRepository.queryHddcB4Sampleresulttables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB4SampleresulttablePage);
    }


    @Override
    public HddcB4SampleresulttableEntity getHddcB4Sampleresulttable(String id) {
        return this.hddcB4SampleresulttableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB4SampleresulttableEntity saveHddcB4Sampleresulttable(HddcB4SampleresulttableEntity hddcB4Sampleresulttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB4Sampleresulttable.setUuid(uuid);
        hddcB4Sampleresulttable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB4Sampleresulttable.setCreateTime(now);
        hddcB4Sampleresulttable.setUpdateTime(now);
        hddcB4Sampleresulttable.setIsValid(PlatformConstants.Y);
        hddcB4Sampleresulttable.setQualityinspectionStatus(PlatformConstants.N);
        hddcB4Sampleresulttable.setExtends10(PlatformConstants.Y);
        this.hddcB4SampleresulttableRepository.save(hddcB4Sampleresulttable);
        return hddcB4Sampleresulttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB4SampleresulttableEntity updateHddcB4Sampleresulttable(HddcB4SampleresulttableEntity hddcB4Sampleresulttable) {
        HddcB4SampleresulttableEntity entity = hddcB4SampleresulttableRepository.findById(hddcB4Sampleresulttable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcB4Sampleresulttable);
        hddcB4Sampleresulttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB4Sampleresulttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB4SampleresulttableRepository.save(hddcB4Sampleresulttable);
        return hddcB4Sampleresulttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB4Sampleresulttables(List<String> ids) {
        List<HddcB4SampleresulttableEntity> hddcB4SampleresulttableList = this.hddcB4SampleresulttableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB4SampleresulttableList) && hddcB4SampleresulttableList.size() > 0) {
            for(HddcB4SampleresulttableEntity hddcB4Sampleresulttable : hddcB4SampleresulttableList) {
//                this.hddcB4SampleresulttableRepository.delete(hddcB4Sampleresulttable);
                hddcB4Sampleresulttable.setIsValid(PlatformConstants.N);
                hddcB4Sampleresulttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB4Sampleresulttable.setUpdateTime(new Date());
                this.hddcB4SampleresulttableRepository.save(hddcB4Sampleresulttable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB4SampleresulttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB4SampleresulttableEntity> yhDisasterEntities = hddcB4SampleresulttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB4SampleresulttableVO> list=new ArrayList<>();
        for (HddcB4SampleresulttableEntity entity:yhDisasterEntities) {
            HddcB4SampleresulttableVO yhDisasterVO=new HddcB4SampleresulttableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"样品测试结果表","样品测试结果表",
                HddcB4SampleresulttableVO.class,"样品测试结果表.xls",response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(fieldSamplingTestResultExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB4SampleresulttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB4SampleresulttableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB4SampleresulttableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcB4SampleresulttableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcB4SampleresulttableVO> list) {
        for (HddcB4SampleresulttableVO hddcB4SampleresulttableVO : list) {
            HddcB4SampleresulttableEntity yhDisasterEntity = new HddcB4SampleresulttableEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcB4SampleresulttableVO, yhDisasterEntity);
            saveHddcB4Sampleresulttable(yhDisasterEntity);
        }
    }


    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB4SampleresulttableEntity> hddcDataList = this.hddcB4SampleresulttableRepository.queryByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB4SampleresulttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB4SampleresulttableRepository.save(entity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcB4SampleresulttableEntity> hddcDataList = this.hddcB4SampleresulttableRepository.queryByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB4SampleresulttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB4SampleresulttableRepository.save(entity);
            }
        }
    }
}
